package com.hospital.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hospital.entity.Medicine;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 药品Mapper接口
 *
 * @author Hospital Management System
 */
@Mapper
public interface MedicineMapper extends BaseMapper<Medicine> {

    /**
     * 查询药品列表（带关联信息）
     */
    @Select("SELECT * FROM tb_medicine " +
            "WHERE deleted = 0 " +
            "AND (#{keyword} IS NULL OR name LIKE CONCAT('%', #{keyword}, '%') " +
            "     OR medicine_code LIKE CONCAT('%', #{keyword}, '%') " +
            "     OR generic_name LIKE CONCAT('%', #{keyword}, '%')) " +
            "ORDER BY create_time DESC")
    List<Medicine> getMedicines(@Param("keyword") String keyword);

    /**
     * 按分类查询药品
     */
    @Select("SELECT * FROM tb_medicine " +
            "WHERE deleted = 0 AND category = #{category} " +
            "ORDER BY name")
    List<Medicine> getMedicinesByCategory(@Param("category") Integer category);

    /**
     * 查询库存不足的药品
     */
    @Select("SELECT * FROM tb_medicine " +
            "WHERE deleted = 0 AND stock_quantity <= safety_stock " +
            "ORDER BY stock_quantity ASC")
    List<Medicine> getLowStockMedicines();

    /**
     * 查询即将过期的药品（30天内）
     */
    @Select("SELECT * FROM tb_medicine " +
            "WHERE deleted = 0 " +
            "AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) " +
            "ORDER BY expiry_date ASC")
    List<Medicine> getNearExpiryMedicines();

    /**
     * 查询已过期的药品
     */
    @Select("SELECT * FROM tb_medicine " +
            "WHERE deleted = 0 AND expiry_date < CURDATE() " +
            "ORDER BY expiry_date ASC")
    List<Medicine> getExpiredMedicines();

    /**
     * 更新药品库存
     */
    @Update("UPDATE tb_medicine SET stock_quantity = stock_quantity + #{quantity} " +
            "WHERE id = #{medicineId}")
    int updateStock(@Param("medicineId") Long medicineId, @Param("quantity") Integer quantity);

    /**
     * 减少药品库存
     */
    @Update("UPDATE tb_medicine SET stock_quantity = stock_quantity - #{quantity} " +
            "WHERE id = #{medicineId} AND stock_quantity >= #{quantity}")
    int reduceStock(@Param("medicineId") Long medicineId, @Param("quantity") Integer quantity);

    /**
     * 获取药品库存统计
     */
    @Select("SELECT " +
            "COUNT(*) as total_medicines, " +
            "SUM(CASE WHEN stock_quantity <= safety_stock THEN 1 ELSE 0 END) as low_stock_count, " +
            "SUM(CASE WHEN expiry_date < CURDATE() THEN 1 ELSE 0 END) as expired_count, " +
            "SUM(CASE WHEN expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as near_expiry_count " +
            "FROM tb_medicine WHERE deleted = 0")
    List<Object> getMedicineStatistics();
} 